// C:\Users\王硕\Desktop\毕设\housing-rental-system-frontend\新建文件夹\vue-demo\src\api\modules\upload.js
import service from "../request";

export default {
  /**
   * 上传用户头像接口
   * @param {File} file - 要上传的文件对象
   * @param {Function} [onProgress] - 上传进度回调函数
   * @returns {Promise<{avatar: string}>} 返回包含头像URL的对象
   */
  uploadAvatar(file, onProgress) {
    const formData = new FormData();
    formData.append("file", file);

    return service
      .post("/api/upload/avatar", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
        onUploadProgress: (progressEvent) => {
          if (typeof onProgress === "function") {
            const percent = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            onProgress(percent);
          }
        },
      })
      .then((response) => {
        // 根据你的后端响应结构处理
        if (response.code === "200") {
          return response.data;
        }
        return Promise.reject(new Error(response.msg || "上传失败"));
      });
  },
};
